package Controller

import (
	"back_go/DAO/gorm"
	"back_go/DAO/gorm/GormModel"
	"back_go/Response"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm/clause"
	"log"
	"math"
	"net/http"
	"strconv"
	"time"
)

// GetUserPage 获取用户分页
/*
current: 当前页码，默认为1
size: 每页数量，默认为10
status: 状态
nickName: 用户名
*/
func GetUserPage(c *gin.Context) {
	currentStr := c.Query("current")
	sizeStr := c.Query("size")
	status := c.Query("status")
	nickName := c.Query("nickName")
	var db = gorm.Db

	var page, size int
	var err error
	if page, err = strconv.Atoi(currentStr); err != nil || page < 1 {
		page = 1
	}
	if size, err = strconv.Atoi(sizeStr); err != nil || size < 1 {
		size = 10
	}
	offset := (page - 1) * size

	// 构建查询条件
	query := db.Table("tz_user") // 更正表名为 tz_user
	if status != "" {
		query = query.Where("status = ?", status)
	}
	if nickName != "" {
		query = query.Where("nick_name LIKE ?", "%"+nickName+"%")
	}

	// 执行查询并获取结果
	var users []GormModel.TzUser
	err = query.Order(clause.OrderByColumn{Column: clause.Column{Name: "user_id"}, Desc: true}).Offset(offset).Limit(size).Find(&users).Error
	if err != nil {
		log.Printf("查询用户失败%v", err)
		c.JSON(200, Response.ResponseBody{
			Code:      "A00005",
			Data:      nil,
			Msg:       "服务器出了问题",
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Fail:      true,
			Success:   false,
		})
		return
	}

	// 计算总数
	var count int64
	err = query.Count(&count).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 构造响应
	c.JSON(http.StatusOK, Response.ResponseBody{
		Code: "00000",
		Data: PageParam1[GormModel.TzUser]{
			Current: page,
			Total:   count,
			Size:    size,
			Records: users,
			Pages:   int(math.Ceil(float64(count) / float64(size))),
		},
		Msg:       nil,
		Success:   true,
		Fail:      false,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
	})
}

// GetUserById 根据id获取用户
/*
   参数：
   	id: 用户id 为varchar类型
     return: 用户信息
*/
func GetUserById(c *gin.Context) {
	var db = gorm.Db
	userId := c.Param("userId")
	var user GormModel.TzUser

	// 使用 err.Error() 获取具体的错误信息
	err := db.Table("tz_user").Where("user_id=?", userId).First(&user).Error
	if err != nil {

		log.Printf("查询用户失败: %v", err.Error())
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00005",
			Data:      nil,
			Msg:       "服务器出了问题",
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Fail:      true,
			Success:   false,
		})

		return
	}

	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:      "00000",
		Data:      user,
		Msg:       nil,
		Success:   true,
		Fail:      false,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
	})
}

// UpdateUser 修改用户信息
/*
   参数：
   	user: 用户信息
     return: 用户信息
*/
func UpdateUser(c *gin.Context) {
	var db = gorm.Db
	var user GormModel.TzUser
	err := c.ShouldBindJSON(&user)
	if err != nil {
		log.Printf("参数错误: %v", err)
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00005",
			Data:      nil,
			Msg:       "服务器出了问题",
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Fail:      true,
			Success:   false,
		})
	}

	//先打印出用户信息
	log.Printf("修改的用户信息: %v", user)
	err = db.Table("tz_user").Where("user_id=?", user.UserId).Updates(&user).Error
	if err != nil {
		log.Printf("更新用户失败: %v", err)
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00005",
			Data:      nil,
			Msg:       "服务器出了问题",
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Fail:      true,
			Success:   false,
		})
		return
	}
	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:    "00000",
		Data:    nil,
		Msg:     nil,
		Success: true,
	})
}

// DeleteUserById 批量删除用户信息
/*
   参数：
   	ids: 用户id列表
     return: 用户信息
*/
func DeleteUserById(c *gin.Context) {
	var db = gorm.Db
	var ids []string
	// 从请求参数中获取id列表
	if err := c.ShouldBindJSON(&ids); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}
	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}
	for _, id := range ids {
		// 删除 tz_user 表中的记录
		if err := tx.Table("tz_user").Where("user_id = ?", id).Delete(&GormModel.TzUser{}).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusOK, gin.H{
				"code": "A00005",
				"msg":  "服务器出了点小差",
			})
			return
		}
	}
	tx.Commit()
	c.JSON(http.StatusOK, gin.H{
		"code":    "00000",
		"msg":     "ok",
		"data":    nil,
		"success": true,
		"version": "1.0",
	})

}
